package chagine.core.serialize.deserializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * Created by lyd on 2017/11/8.
 * 反序列换的时候用于金额换算，从元换算成分
 * 传入的 double (以元为单位的值) 换算成 Integer
 */
@Slf4j
public class MoneyDeserializer extends JsonDeserializer<Integer> {

    @Override
    public Integer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        if (StringUtils.isBlank(p.getText())) {
            return null;
        }
        try {
            return new BigDecimal(p.getText()).multiply(new BigDecimal(100)).intValue();
        } catch (Exception ignore) {
            return null;
        }
    }

}
